import { Button, Col, Form, Input, message, Modal, Radio, Row } from "antd"
import Checkbox, { CheckboxGroupProps } from "antd/es/checkbox"
import { useEffect, useState } from "react"
import style from "./index.module.css"
import { reqGetCatpcha } from "../../api/other"
import { reqGetUserById, reqLogin, reqSignIn } from "../../api/user"
import { reqLoginForm, reqSignForm } from "../../Types/Api/user"
import { useDispatch } from "react-redux"
import { changeLoginState, initUser } from "../../store/userSlice"
type Props = {
  isShow: boolean
  close: () => void
}
type FieldType = {
  loginId?: string
  loginPwd?: string
  remember?: string
  captcha?: string
  nickname?: string
}
export const LoginForm = ({ isShow, close }: Props) => {
  const dispatch = useDispatch()
  //   全局提示
  const [messageApi, contextHolder] = message.useMessage()
  // 登录注册按钮
  const options: CheckboxGroupProps<string>["options"] = [
    { label: "登录", value: "login" },
    { label: "注册", value: "signIn" },
  ]
  const [type, setType] = useState("login")
  const changeType = (val: string) => {
    // console.log(val)
    setType(val)
  }

  // 验证码
  const [yzmStr, setYzmStr] = useState("")
  const getCode = async () => {
    const code = await reqGetCatpcha()
    setYzmStr(code)
  }

  // 登录/注册表单
  const onLoginFinish = async (e: reqLoginForm) => {
    const { data, msg, code } = await reqLogin(e)
    if (code !== 0) {
      // 全局提示
      messageApi.error(msg)

      getCode()
    } else {
      // 验证码是正确的
      if (data.data.enabled === false) {
        // 账号封禁
      } else {
        // 登录成功
        // 存储用户信息
        const { data: user } = await reqGetUserById(data.data._id)
        dispatch(changeLoginState(true))
        dispatch(initUser(user))
        // 存token
        localStorage.setItem("token", data.token)
        // 关闭Modal
        close()
      }
    }
  }
  const onSignFinish = async (e: reqSignForm) => {
    const { code, data, msg } = await reqSignIn(e)
    if (code !== 0) {
      messageApi.error(msg)
    } else {
      // 注册成功
      messageApi.success("注册成功，初始密码为123456")
      // 隐藏弹窗
      close()
      // 更新用户信息
      dispatch(changeLoginState(true))
      dispatch(initUser(data))
    }
  }

  let form: JSX.Element
  if (type === "login") {
    // 生成专属于Login Form
    form = (
      <Form
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: false }}
        onFinish={onLoginFinish}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="用户名"
          name="loginId"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="密码"
          name="loginPwd"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item<FieldType>
          label="验证码"
          name="captcha"
          rules={[{ required: true, message: "请输入验证码!" }]}
        >
          <Row align="middle">
            <Col span={8}>
              <Input />
            </Col>
            <Col offset={4} span={12}>
              <div
                onClick={getCode}
                dangerouslySetInnerHTML={{ __html: yzmStr }}
              ></div>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item<FieldType>
          name="remember"
          valuePropName="checked"
          label={null}
        >
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item label={null}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ marginRight: "20px" }}
          >
            登录
          </Button>
          <Button type="dashed" htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    )
  } else {
    // 注册的Form;
    form = (
      <Form
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: false }}
        onFinish={onSignFinish}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="用户名"
          name="loginId"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="昵称"
          name="nickname"
          rules={[{ required: true, message: "请输入昵称!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="验证码"
          name="captcha"
          rules={[{ required: true, message: "请输入验证码!" }]}
        >
          <Row align="middle">
            <Col span={8}>
              <Input />
            </Col>
            <Col offset={4} span={12}>
              <div
                onClick={getCode}
                dangerouslySetInnerHTML={{ __html: yzmStr }}
              ></div>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item label={null}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ marginRight: "20px" }}
          >
            注册
          </Button>
          <Button type="dashed" htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    )
  }

  useEffect(() => {
    getCode()
  }, [isShow, type])
  return (
    <>
      {contextHolder}
      <Modal open={isShow} onCancel={close} footer={null} title="登录/注册">
        <Radio.Group
          block
          options={options}
          defaultValue="login"
          optionType="button"
          buttonStyle="solid"
          onChange={(e) => changeType(e.target.value)}
        />
        <div className={style.formWrapper}>{form}</div>
      </Modal>
    </>
  )
}
